const https = require('https');

exports.handler = async (event, context, callback) => {
  // 处理预检请求（CORS）
  if (context.httpMethod === 'OPTIONS') {
    callback(null, {
      statusCode: 204,
      headers: {
        'Access-Control-Allow-Methods': 'POST,OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type',
      },
      body: ''
    });
    return;
  }

  // 解析前端传来的 JSON（适配阿里云 HTTP 触发器新版格式）
  let reqBody = {};
  try {
    const eventObj = JSON.parse(event.toString());
    reqBody = JSON.parse(eventObj.body || '{}');
    console.log('reqBody:', reqBody);
  } catch (e) {
    callback(null, {
      statusCode: 400,
      headers: {
        'Access-Control-Allow-Methods': 'POST,OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ errcode: 400, errmsg: 'Invalid JSON' })
    });
    return;
  }

  // 组装钉钉普通文本消息内容
  const postData = JSON.stringify({
    msgtype: 'text',
    text: { content: '[系统通知]' + (reqBody.content || '') }
  });

  const webhook = 'https://oapi.dingtalk.com/robot/send?access_token=你的真实token'; // 换成你的钉钉机器人token
  const url = new URL(webhook);
  const options = {
    hostname: url.hostname,
    path: url.pathname + url.search,
    method: 'POST',
    headers: { 'Content-Type': 'application/json' }
  };

  let dingRes = '';
  try {
    dingRes = await new Promise((resolve, reject) => {
      const req2 = https.request(options, res2 => {
        let data = '';
        res2.on('data', chunk => data += chunk);
        res2.on('end', () => resolve(data));
      });
      req2.on('error', reject);
      req2.write(postData);
      req2.end();
    });
  } catch (e) {
    callback(null, {
      statusCode: 500,
      headers: {
        'Access-Control-Allow-Methods': 'POST,OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ errcode: 500, errmsg: 'DingTalk request failed', detail: e.message })
    });
    return;
  }

  callback(null, {
    statusCode: 200,
    headers: {
      'Access-Control-Allow-Methods': 'POST,OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
      'Content-Type': 'application/json'
    },
    body: dingRes
  });
}; 